<?php


namespace WxWorkSDK\Department;


use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

class UpdateDepartment
{
    const URI = "department/update";
    /**
     * @var string
     * @annotation
     */
    private $accessToken = '';
    /**
     * @var string
     * @annotation
     */
    private $name = '';
    /**
     * @var null
     * @annotation
     */
    private $parentId = NULL;
    /**
     * @var null
     * @annotation
     */
    private $order = NULL;
    /**
     * @var null
     * @annotation
     */
    private $id = NULL;

    /**
     * CreateDepartment constructor.
     * @param string   $accessToken
     * @param string   $name
     * @param int      $parentId
     * @param int|NULL $order
     * @param int|NULL $id
     */
    public function __construct(string $accessToken, string $name, int $parentId, int $order = NULL, int $id = NULL)
    {
        $this->accessToken = $accessToken;
        $this->name        = $name;
        $this->parentId    = $parentId;
        $this->order       = $order;
        $this->id          = $id;
    }

    /**
     * @return Result
     * @annotation
     */
    public function update(): Result
    {
        if ($check = $this->check() != 0) {
            return new Result(FALSE, Error::PARAM_MISTAKE, $check);
        }
        $postData = [
            'access_token' => $this->accessToken,
            'id'           => $this->id
        ];
        if (!empty($this->order)) {
            $postData['order'] = $this->order;
        }
        if (!empty($this->name)) {
            $postData['name'] = $this->name;
        }
        if (!empty($this->parentId)) {
            $postData['parentid'] = $this->parentId;
        }
        list($bool, $response) = Http::request('POST', self::URI, ['query' => $postData]);
        if ($bool) {
            return $this->response($response);
        } else {
            return $response;
        }
    }

    /**
     * @return int|string
     * @annotation
     */
    private function check()
    {
        if (empty($this->accessToken)) {
            return '无TOKEN';
        }
        if (empty($this->id)) {
            return '无部门ID';
        }
        if (empty($this->parentId) && empty($this->name) && empty($this->order)) {
            return '无更新数据';
        }
        return 0;
    }

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function response($response): Result
    {
        $response = json_decode($response, TRUE);
        if ($response['errcode'] == 0) {
            return new Result(TRUE, 0, 'ok');
        } else {
            return new Result(FALSE, Error::WX_MISTAKE, $response['errcode'] . ':' . $response['errmsg']);
        }
    }
}